package com.juzhencms.apps.busi.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.juzhencms.apps.base.busi.service.WeixinApiService;
import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.HttpUtil;
import com.juzhencms.apps.base.common.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class AppMenuService extends CommonService {
	@Autowired
	private WeixinApiService weixinApiService;
	public Map getWeiXinMenu(int siteID) {		
		/*	自定义菜单最多包括3个一级菜单，每个一级菜单最多包含5个二级菜单。
		一级菜单最多4个汉字，二级菜单最多7个汉字，多出来的部分将会以“...”代替。*/
		Map result=new HashMap();
		result.put("result", 1);
		ArrayList weiXinMenuList = new ArrayList();
		String sql="SELECT * FROM "+DBTable.appMenu+" where del_flag=0 and publish=1 and  site_id=? and parent_id=0  order by position ASC LIMIT 0,3";
		List parentList=this.getJdbcDao().querySql(sql,new Object[] {siteID});
		if(parentList!=null && parentList.size()>0) {
			for(int i=0;i<parentList.size();i++) {
				Map menuInfo=(Map) parentList.get(i);
				sql="SELECT * FROM "+DBTable.appMenu+" where del_flag=0 and publish=1 and  site_id=? and parent_id=?  order by position ASC LIMIT 0,5";
				List subList = this.getJdbcDao().querySql(sql, new Object[] {siteID,menuInfo.get("id")});
				if(subList!=null && subList.size()>0) {
					
					ArrayList _subList = new ArrayList();					
					for(int n=0;n<subList.size();n++) {
						Map subInfo=(Map) subList.get(n);
						Map tempMap=this.makeMenuInfo(subInfo);
						if("1".equals(tempMap.get("result")+"")) {							
							_subList.add(tempMap.get("weiXinMenu"));
						}else if("2".equals(tempMap.get("result")+"")){//链接失效
							
						}else  {
							result.put("result", 0);
							result.put("msg", tempMap.get("msg"));
							return result;
						}										
					}
				    Map tempMap=new HashMap();
				    tempMap.put("name", menuInfo.get("name"));
				    if(_subList.size()>0) { //如果存在下级菜单就保存否则一级菜单失效
				    	 tempMap.put("sub_button",_subList);
				    	 weiXinMenuList.add(tempMap);	
				    }				   			    
				}else { //没有二级菜单
					Map tempMap=this.makeMenuInfo(menuInfo);
					if("1".equals(tempMap.get("result")+"")) {
						weiXinMenuList.add(tempMap.get("weiXinMenu"));
					}else if("2".equals(tempMap.get("result")+"")){ //链接失效
						
					}else {
						result.put("result", 0);
						result.put("msg", tempMap.get("msg"));
						return result;
					}					
				}
			}
			result.put("weiXinMenuList", weiXinMenuList);
		}else {
			result.put("result", 0);
			result.put("msg", "暂无菜单信息！");
		}
		
		return result;
	}
	//图片（image）、视频（video）、语音 （voice）、图文（news）
	public Map makeMenuInfo(Map menu) {
		Map result=new HashMap();
		Map weiXinMenu=new HashMap();			
		weiXinMenu.put("name", menu.get("name"));
		result.put("result", 1);
		//1发送消息，2链接跳转,3小程序
		if("1".equals(menu.get("type")+"")) {
			if("news".equals(menu.get("message_type")+"") || "image".equals(menu.get("message_type")+"") || "video".equals(menu.get("message_type")+"") || "voice".equals(menu.get("message_type")+"")  ) {
				weiXinMenu.put("type", "media_id");
				weiXinMenu.put("media_id", menu.get("media_id"));				
				//如果此条medi——id已经被删除则当前菜单失效
				int sourceID=new Integer(menu.get("weixin_source_id")+"");
				Map weixinSource=this.getAppWeixinSourceMapper().get(sourceID);
				if(weixinSource==null || weixinSource.size()==0) {
					result.put("result", 2);
				}			
			}else if("text".equals(menu.get("message_type")+"")){ //文字
				weiXinMenu.put("type", "click");
				weiXinMenu.put("key", menu.get("click_key"));
			}else{
				result.put("result", 0);
				result.put("msg", menu.get("name")+"菜单配置有误！");
				return result;
			}
		}else if("2".equals(menu.get("type")+"")) { //链接跳转
			weiXinMenu.put("type", "view");
			if(StringUtil.isNotNullOrEmpty(menu.get("url_link_data"))) {
				if("0".equals(menu.get("url_link_data")+"")) {
					weiXinMenu.put("url", menu.get("url"));
				}else if("2".equals(menu.get("url_link_data")+"")){ //文章单页
					weiXinMenu.put("type", "view_limited");
					weiXinMenu.put("media_id", menu.get("media_id"));					
				}else if("1".equals(menu.get("url_link_data")+"")){
					String url=Config.getValue("app.domain")+"newsList_"+menu.get("url_link_category_id")+"_page1";
					weiXinMenu.put("url",url);
				}else {
					result.put("result", 0);
					result.put("msg", menu.get("name")+"菜单配置有误！");
					return result;
				}
			}else {
				result.put("result", 0);
				result.put("msg", menu.get("name")+"菜单配置有误！");
				return result;
			}			
		}else if("3".equals(menu.get("type")+"")) { //小程序跳转
			weiXinMenu.put("type", "miniprogram");
			weiXinMenu.put("appid", menu.get("appid"));
			weiXinMenu.put("pagepath", menu.get("pagepath"));
			if(StringUtil.isNotNullOrEmpty(menu.get("url"))) {
				weiXinMenu.put("url", menu.get("url"));
			}else {
				result.put("result", 0);
				result.put("msg", menu.get("name")+"菜单配置有误！");
				return result;
			}			
		}else {
			result.put("result", 0);
			result.put("msg", menu.get("name")+"菜单配置有误！");
			return result;
		}
		result.put("weiXinMenu", weiXinMenu);		
		return result;
	}
	
	public Map publishWeiXinMenu(int siteID) {
		//String access_token=this.siteSettingService.getWeixinAccessToken(siteID);
		String access_token=this.weixinApiService.getAccessTokenBySiteID(siteID);
		Map result=new HashMap();
		if(StringUtil.isNullOrEmpty(access_token)){
			result.put("result", 0);
			result.put("msg", "access_token获取失败");
			return result;
		}
		Map resultMap=this.getWeiXinMenu(siteID);
		
		log.info(resultMap+"=====publishWeiXinMenupublishWeiXinMenupublishWeiXinMenupublishWeiXinMenu");
		if("1".equals(resultMap.get("result")+"")) {
			
			
			ArrayList weiXinMenuList=(ArrayList) resultMap.get("weiXinMenuList");
			Map postParam=new HashMap();
			postParam.put("button", weiXinMenuList);
			JSONObject jsonObj=new JSONObject(postParam);
			log.info(jsonObj.toString());
			
			String url=Config.getValue("weixin.apiURL")+"/menu/create?access_token="+access_token;
			String postResult=HttpUtil.post(url,jsonObj.toString());
			Map postResultMap=JSON.parseObject(postResult,Map.class);
			log.info("postResult====="+postResult);
			if("0".equals(postResultMap.get("errcode")+"")) {
				result.put("result", 1);
				result.put("msg", "发布成功，将在24小时内对所有用户生效");
			}else {
				result.put("result", 0);
				result.put("msg", postResultMap.get("errmsg"));
				return result;
			}
		}else {
			result.put("result", 0);
			result.put("msg", resultMap.get("msg"));
		}
		return result;
	}
	
	
	
}
